<script setup>
import { ref, reactive, onMounted, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {Plus, Edit, Delete, Search} from '@element-plus/icons-vue'

//引入API
// import {} from '../../api/performance.js'
// import {} from '../../api/emp.js'

const tableLoading = ref(true);
// 数据
const currentPageNum = ref(1);//当前页码
const currentPageSize = ref(5);//每页显示的最大数据量
const dataArr = ref([]);//当前页数据
const total = ref(0);//总数据量

function doLoadTableDatas() {//加载表格数据
    tableLoading.value = true;//开始加载
    //TODO: 使用API根据条件加载数据
    //主要查询条件
    let params = {
        pageNum: currentPageNum.value,
        pageSize: currentPageSize.value,
        no: searchFormData.value.no,
        month: searchFormData.value.month,
    };
    console.log('search params:', params);

    //模拟数据加载操作
    const loadData = () => {
        return {
            total: 100,
            data: [
                {id:1,no:'000001',name:'汤姆1',score:80,money:0,recordDate:'2024-07-16 14:30:20',remark:''},
                {id:2,no:'000002',name:'汤姆2',score:85,money:0,recordDate:'2024-07-16 14:30:20',remark:''},
                {id:3,no:'000003',name:'汤姆3',score:90,money:100,recordDate:'2024-07-16 14:30:20',remark:'全勤'},
                {id:4,no:'000004',name:'汤姆4',score:84,money:0,recordDate:'2024-07-16 14:30:20',remark:''},
                {id:5,no:'000005',name:'汤姆5',score:91,money:100,recordDate:'2024-07-16 14:30:20',remark:'全勤'},
            ]
        }
    };
    const result = loadData();

    //成功后执行以下操作
    //处理响应数据
    dataArr.value = result.data;
    total.value = result.total;
    tableLoading.value = false;//加载完成

}

onMounted(()=> {//挂载后执行
    doLoadTableDatas();//核心表格数据
    doLoadAllEmps();
});

const tableSelectObj = ref(null);//选中行对象
function doTableSelectionChange(selected) {//选中操作
    //选中变化
    console.log('doTableSelectionChange:', selected);
    tableSelectObj.value = selected;
}

function doAddAll() {
    //TODO: 增加某一月所有员工的初始继续考核记录信息,以便后续录入每个员工绩效考核信息

    //成功后执行以下操作
    ElMessage.success('所有员工的初始继续考核记录信息添加成功');
    doLoadTableDatas();
}
function doToggleAddOne() {
    //增加一个员工考核记录
    addFormHeight.value = addFormHeight.value == 0 ? 350:0;
}

//一次只能操作一个数据
function doModify() {//修改对话框
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要修改的行');
        return;
    }
    //设置数据
    const obj = toRaw(tableSelectObj.value);//取原对象
    const newValue = structuredClone(obj);//克隆
    formData.value = newValue;

    //成功后打开对话框
    dialogFlag.value = true;
}
function doRemove() {//删除
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要删除的行');
        return;
    }
    //TODO: 执行数据删除

    //成功后执行以下操作
    ElMessage.success('删除成功');
    //重新加载数据
    doLoadTableDatas();
}

function createFormData() {//表单数据对象模板
    return {id:undefined,no:'',name:'',score:0,money:0,recordDate:'',remark:''};
}
//对话框中表单数据
const formData = ref(createFormData());
const dialogFlag = ref(false);
function doDialogBeforeClose(done) {
    //关闭操作
    done();
    formRef.value.clearValidate();//清除校验标记
}
function doCloseDialog(type) {
    if(type === 0) {
        //取消操作
        dialogFlag.value = false;
        formRef.value.clearValidate();//清除校验标记
        return;
    }
    if(type === 1) {
        //确定操作
        doFormSubmit();
    }
}
const formRef = ref(null);//表单组件
const formRules = reactive({//校验规则
    score: [{required:true, validator: (rule, value, callback)=>{
        if(value === '') {
            callback(new Error('请填写分数'));
            return;
        }
        if(value < 0) {
            callback(new Error('分数不能小于0'));
            return;
        }
        if(value > 100) {
            callback(new Error('分数不能大于100'));
            return;
        }
        callback();
    }, trigger:'blur'}],
    money: [{required:true, validator: (rule, value, callback)=>{
        if(value === '') {
            callback(new Error('请填写金额'));
            return;
        }
        callback();
    }, trigger:'blur'}],
    recordDate: [{required:true, validator: (rule, value, callback)=>{
        if(value === null || value === undefined || value === '') {
            callback(new Error('请填写记录时间'));
            return;
        }
        callback();
    }, trigger:'change'}],
    remark: [
        {required:false, min:1, max:10, message:'备注内容长度是1~100', trigger:'blur'},
    ]
});
function doFormSubmit() {//表单校验与提交
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交修改的数据
            let params = toRaw(formData.value);
            console.log('submit:', params);

            //成功后执行以下操作
            dialogFlag.value = false;//成功,关闭对话框
            ElMessage.success('修改成功');
            //重新加载数据
            doLoadTableDatas();
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}

//搜索
const searchFormData = ref({no:'', month:''});
const searchFormRef = ref(null);
function doFormSearch() {
    if(tableLoading.value) {
        ElMessage.warning('正在查询中...');
        return;
    }
    //console.log('searchFormData:', toRaw(searchFormData.value));
    let oldPageNum = currentPageNum.value;
    currentPageNum.value = 1;//从头开始查询
    if(oldPageNum == 1) {//防止重复加载
        // 根据条件加载数据
        doLoadTableDatas();
    }
}

//分页变化,加载数据
watch(currentPageNum, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});
watch(currentPageSize, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});

//增加一条记录
const addFormData = ref({empId:undefined,score:0,money:0,recordDate:'',remark:''});
const addFormRef = ref(null);//表单组件
const addFormRules = reactive({//校验规则
    empId: [{required:true, message:'请选择员工', trigger:'change'}],
    score: [{required:true, validator: (rule, value, callback)=>{
        if(value === '') {
            callback(new Error('请填写分数'));
            return;
        }
        if(value < 0) {
            callback(new Error('分数不能小于0'));
            return;
        }
        if(value > 100) {
            callback(new Error('分数不能大于100'));
            return;
        }
        callback();
    }, trigger:'blur'}],
    money: [{required:true, validator: (rule, value, callback)=>{
        if(value === '') {
            callback(new Error('请填写金额'));
            return;
        }
        callback();
    }, trigger:'blur'}],
    recordDate: [{required:true, validator: (rule, value, callback)=>{
        if(value === null || value === undefined || value === '') {
            callback(new Error('请填写记录时间'));
            return;
        }
        callback();
    }, trigger:'change'}],
    remark: [
        {required:false, min:1, max:10, message:'备注内容长度是1~100', trigger:'blur'},
    ]
});
function doAddFormSubmit() {
    addFormRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交添加的数据
            let params = toRaw(addFormData.value);
            console.log('addFormData:', params);

            //成功后执行以下操作
            ElMessage.success('添加成功');
            //重新加载数据
            doLoadTableDatas();
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}
function doAddFormReset() {//表单重置
    addFormRef.value.resetFields();
}
function doAddFormClose() {
    addFormHeight.value = 0;//隐藏表单
    addFormRef.value.resetFields();//重置表单
}

const addFormHeight = ref(0);
const empArr = ref([]);
function doLoadAllEmps() {
    //使用API加载数据
    //模拟数据加载
    setTimeout(()=>{
        let data = [
            {id:1,name:'汤姆1',no:'000001'},
            {id:2,name:'汤姆2',no:'000002'},
            {id:3,name:'汤姆3',no:'000003'}
        ];

        //成功后执行以下操作
        empArr.value = data;
    },500);
}

</script>
<template>
    <div>
        <div class="title-dl">绩效考核记录列表</div>
        <div class="tool-btns" >
            <!-- search表单 -->
            <el-form :model="searchFormData" :inline="true" ref="searchFormRef" >
                <el-form-item label="员工工号：" prop="no">
                    <el-input v-model="searchFormData.no" autocomplete="off" placeholder="请输入员工工号" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="考核月份：" prop="month">
                    <el-date-picker type="month" v-model="searchFormData.month" placeholder="选择月份" format="YYYY-MM" value-format="YYYY-MM" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="doFormSearch">查询</el-button>
                </el-form-item>
            </el-form>
            <el-button type="success" :icon="Plus" @click="doAddAll">增加全员考核记录</el-button>
            <el-button type="primary" :icon="Plus" @click="doToggleAddOne">增加一条考核记录</el-button>
            <el-button type="warning" :icon="Edit" @click="doModify">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="doRemove">删除</el-button>

            <div class="add-form-dl" :style="{height: addFormHeight+'px'}" >
                <div class="title-dl">绩效考核</div>
                <!-- 新增一条考核记录 -->
                <el-form :model="addFormData" label-width="130px" :rules="addFormRules" 
                status-icon ref="addFormRef">
                    <el-form-item label="员工：" prop="empId">
                        <!-- <el-input v-model="addFormData.no" autocomplete="off" readonly /> -->
                        <el-select v-model="addFormData.empId" placeholder="请选择员工" >
                            <el-option v-for="p in empArr" :key="p.id" :label="p.name+'('+p.no+')'" :value="p.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分数(满分100)：" prop="score">
                        <el-input type="number" v-model.number="addFormData.score" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="奖惩金额(元)：" prop="money">
                        <el-input type="number" v-model.number="addFormData.money" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="备注：" prop="remark">
                        <el-input type="textarea" v-model="addFormData.remark" autocomplete="off" autosize :maxlength="100" show-word-limit />
                    </el-form-item>
                    <el-form-item label="记录时间：" prop="recordDate">
                        <el-date-picker type="datetime" v-model="addFormData.recordDate" placeholder="选择时间" value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="doAddFormSubmit">确定</el-button>
                        <el-button @click="doAddFormReset" >重置</el-button>
                        <el-button type="info" @click="doAddFormClose" >关闭</el-button>
                    </el-form-item>
                </el-form>
            </div>

        </div>
        <div class="content-dl" v-loading="tableLoading" >
            <!-- 根据情况增减列 -->
            <el-table :data="dataArr" stripe border @current-change="doTableSelectionChange" highlight-current-row>
                <el-table-column prop="no" label="员工工号" width="120" show-overflow-tooltip  />
                <el-table-column prop="name" label="姓名" show-overflow-tooltip />
                <el-table-column prop="score" label="分数" width="100" show-overflow-tooltip />
                <el-table-column prop="money" label="奖惩金额" width="120" show-overflow-tooltip />
                <el-table-column prop="recordDate" label="记录时间" width="200" show-overflow-tooltip />
                <el-table-column prop="remark" label="备注" show-overflow-tooltip />
            </el-table>
            <el-pagination class="page-dl" layout="total, jumper, prev, pager, next" :total="total"
            v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :pager-count="5" hide-on-single-page size="large" />
        </div>

        <!-- 修改对话框 destroy-on-close关闭时销毁 -->
        <el-dialog v-model="dialogFlag" title="绩效考核记录编辑" width="500" 
        :before-close="doDialogBeforeClose" center align-center draggable
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        >
            <el-form :model="formData" label-width="130px" :rules="formRules" 
            status-icon ref="formRef">
                <el-form-item label="员工工号：" prop="no">
                    <el-input v-model="formData.no" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="formData.name" autocomplete="off" readonly />
                </el-form-item>
                <el-form-item label="分数(满分100)：" prop="score">
                    <el-input type="number" v-model.number="formData.score" autocomplete="off" />
                </el-form-item>
                <el-form-item label="奖惩金额(元)：" prop="money">
                    <el-input type="number" v-model.number="formData.money" autocomplete="off" />
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input type="textarea" v-model="formData.remark" autocomplete="off" autosize :maxlength="100" show-word-limit />
                </el-form-item>
                <el-form-item label="记录时间：" prop="recordDate">
                    <el-date-picker type="datetime" v-model="formData.recordDate" placeholder="选择时间" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="doCloseDialog(0)">取消</el-button>
                    <el-button type="primary" @click="doCloseDialog(1)">确定</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<style scoped>
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
.tool-btns {
    margin-bottom: 10px;
}
.add-form-dl {
    margin-top: 10px;
    width: 600px;
    overflow-y: auto;
    transition: height 0.5s linear;
}
.page-dl {
    margin-top: 10px;
}
</style>
